function [error] = rank_err(prediction, actual)

%This function computes the rank error of a set of predictions according to
%the formula:
%    error = 1/n * sum(1 - 1/ri)

% ACTUAL is an Nx1 vector of the actual labels. PREDICTION is an Nx10
% vector where the elements are probabilities.
% The output ERROR will be a scalar.

K = 10;                                         % number of classes 
n = size(prediction,1);                         % number of examples
ind = zeros(n,1);                               % rank of correct class

%ranks will be an Nx10 vector that gives the ordered predicted class (in terms of an
%actual class number, not a row of probabilities)
for i=1:n
    unsorted_row = [prediction(i,:); 1:K]; %add a row of 1:K to play the role of indicies
    sorted_row = fliplr( transpose ( sortrows( unsorted_row'))); %sort row on the first row (probabilities)
    ind(i) = find( sorted_row(2,:) == actual(i) );
end

error = (1/n)*sum(1-1./(ind),1);


